package org.openrbac.rbac.config;

import org.openrbac.rbac.filter.SecurityJwtAuthenticationFilter;
import org.openrbac.rbac.handler.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

/**
 * @author bapie
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig {
    @Autowired
    private CorsConfigurationSource corsConfigurationSource;

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedMethods(Arrays.asList( "GET", "POST", "DELETE", "PUT", "PATCH", "OPTIONS"));
        configuration.setAllowedOrigins(Arrays.asList("*"));
        configuration.setAllowedHeaders(Arrays.asList("*"));
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
    @Bean
    public AntPathMatcher antPathMatcher() {
        return new AntPathMatcher();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http,
                                           SecurityAuthenticationSuccessHandler securityAuthenticationSuccessHandler,
                                           SecurityAuthenticationFailureHandler securityAuthenticationFailureHandler,
                                           SecurityAuthenticationAccessHandler securityAuthenticationAccessHandler,
                                           SecurityLogoutSuccessHandler securityLogoutSuccessHandler,
                                           SecurityAuthenticationEntryPointHandler securityAuthenticationEntryPointHandler,
                                           SecurityAuthenticationAccessDeniedHandler securityAuthenticationAccessDeniedHandler,
                                           SecurityJwtAuthenticationFilter securityJwtAuthenticationFilter
    ) throws Exception {

        http.cors().configurationSource(corsConfigurationSource);
        http
                .csrf().disable()
                .authorizeHttpRequests(authorize -> authorize
                        .antMatchers("/login", "/logout", "/error").permitAll()
                        .antMatchers("/static","/public/**","/image/**","/catalogue/**").permitAll()
                        .anyRequest().access((authentication, request) -> securityAuthenticationAccessHandler.check(authentication, request.getRequest()))
                        .and().addFilterBefore(securityJwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                )
                .sessionManagement(customizer -> customizer
                        .sessionCreationPolicy(SessionCreationPolicy.NEVER))
                .logout(customizer -> customizer
                        .logoutSuccessHandler(securityLogoutSuccessHandler)
                        .permitAll()
                )
                .exceptionHandling(customizer -> customizer
                        .authenticationEntryPoint(securityAuthenticationEntryPointHandler)
                        .accessDeniedHandler(securityAuthenticationAccessDeniedHandler)
                )
                .formLogin(customizer -> customizer
                        .successHandler(securityAuthenticationSuccessHandler)
                        .failureHandler(securityAuthenticationFailureHandler));
        return http.build();
    }


}
